package lumis.portal.presentation.perspective.admin;

import java.util.ArrayList;
import java.util.Collection;

import lumis.portal.authentication.SessionConfig;
import lumis.portal.presentation.PageRendererUtil;
import lumis.portal.presentation.core.LayoutFilePage;
import lumis.portal.presentation.tag.page.RenderHolderComponent;
import lumis.portal.transaction.PortalTransactionFactory;

import org.apache.wicket.Component;
import org.apache.wicket.behavior.AbstractBehavior;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.w3c.dom.Document;

/**
 * Panel that renders the holders present in the page layout that has not
 * been rendered in the page.
 *
 * @version $Revision: 13093 $ $Date: 2011-05-28 18:40:18 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */
@SuppressWarnings("serial")
public class RemainingHoldersPanel extends Panel
{
	public RemainingHoldersPanel(String id)
	{
		super(id);
	}
	
	protected void onBeforeRender()
	{
		LayoutFilePage page = (LayoutFilePage)getPage();
		
		// get holder ids in the page layout
		Document document = PageRendererUtil.getPageLayout(SessionConfig.getCurrentSessionConfig(), page.getPageWebResource(), PortalTransactionFactory.getCurrentTransaction(), page.getPortalMode().getPerspective().value());

		final Collection<String> holderIds = PageRendererUtil.getPageLayoutHolderIds(document, page.getPageWebResource());

		if (!holderIds.isEmpty())
		{
			// remove holders already included in the page
			page.visitChildren(RenderHolderComponent.class, new IVisitor<RenderHolderComponent>()
			{
				public Object component(RenderHolderComponent component)
				{
					holderIds.remove(component.getHolderId());
					return CONTINUE_TRAVERSAL_BUT_DONT_GO_DEEPER;
				}
			});
		}
		
		if (holderIds.isEmpty())
		{
			setVisible(false);
		}
		else
		{
			// loop through remaining holders, rendering them
			add(new ListView<String>("remainingHolders", new ArrayList<String>(holderIds))
			{
				@Override
				protected void populateItem(ListItem<String> item)
				{
					RenderHolderComponent renderHolderComponent = new RenderHolderComponent("holder", item.getModelObject(), false);
					renderHolderComponent.add(new AbstractBehavior()
					{
						@Override
						public void onComponentTag(Component component, ComponentTag tag)
						{
							super.onComponentTag(component, tag);
							tag.put("lumRemainingHolder", "true");
						}
					});
					item.add(renderHolderComponent);
				}
			});
		}
		
		super.onBeforeRender();
	}
}
